﻿using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using Microsoft.Win32.SafeHandles;
using System.IO;
using System.Diagnostics;
public class ServiceInteractiveSession
{
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    static extern bool CloseHandle(IntPtr handle);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern bool DuplicateTokenEx(
        IntPtr hExistingToken,
        uint dwDesiredAccess,
        IntPtr lpTokenAttributes,
        int ImpersonationLevel,
        int TokenType,
        out IntPtr phNewToken);

    [DllImport("advapi32.dll")]
    static extern bool RevertToSelf();

    const int TOKEN_QUERY = 0x0008;
    const int TOKEN_DUPLICATE = 0x0002;
    const int SecurityImpersonation = 2;
    const int TokenPrimary = 1;

    public static bool SetServiceInteractiveSession()
    {
        IntPtr tokenHandle = IntPtr.Zero;
        IntPtr duplicateTokenHandle = IntPtr.Zero;
        try
        {
            // 获取当前进程的令牌
            tokenHandle = WindowsIdentity.GetCurrent().Token;

            // 复制当前令牌
            if (!DuplicateTokenEx(tokenHandle, TOKEN_QUERY | TOKEN_DUPLICATE, IntPtr.Zero, SecurityImpersonation, TokenPrimary, out duplicateTokenHandle))
            {
                return false;
            }

            // 创建一个新的WindowsIdentity来使用复制的令牌
            using (WindowsIdentity tempIdentity = new WindowsIdentity(duplicateTokenHandle))
            {
                using (WindowsImpersonationContext impersonationContext = tempIdentity.Impersonate())
                {
                    // 在这里写你的代码，它将在用户的会话环境中运行
                    // ...
                    // 打开默认的打印对话框
                    ProcessStartInfo startInfo = new ProcessStartInfo
                    {
                        FileName = @"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
                        Arguments = @"E:\MergedWithPageNumbers.pdf",
                        UseShellExecute = true,
                        CreateNoWindow = false,
                        WindowStyle = ProcessWindowStyle.Normal,
                        Verb = "runas",
                    };
                    Process.Start(startInfo);
                    // 撤销模拟
                    impersonationContext.Undo();
                }
            }

            return true;
        }
        finally
        {
            // 释放令牌句柄
            if (tokenHandle != IntPtr.Zero)
                CloseHandle(tokenHandle);

            if (duplicateTokenHandle != IntPtr.Zero)
                CloseHandle(duplicateTokenHandle);
        }
    }
}